package org.os.framework.context.utils;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * 对象工具
 * 
 * @author
 */
@Slf4j
public class ObjectUtil {

    /**
     * 获取对象getter
     * 
     * @param obj
     * @return
     */
    public static Map<String, Object> getters(Object obj) {
        if (null == obj) {
            return Collections.emptyMap();
        }
        Map<String, Object> kv = new HashMap<>(16);
        for (Method method : obj.getClass().getDeclaredMethods()) {
            String key = method.getName();
            Object value = null;
            try {
                value = method.invoke(obj);
            } catch (Exception e) {
                log.info("error =>", e);
            }
            kv.put(key, value);
        }
        return kv;
    }

    /**
     * key转驼峰
     * 
     * @param <K>
     * @param <V>
     * @param originalMap
     * @return
     */
    public static <K, V> Map<String, V> convertKeysToCamelCase(Map<K, V> originalMap) {
        return originalMap.entrySet().stream()
                .collect(Collectors.toMap(
                        entry -> convertHyphenToCamelCase(entry.getKey().toString()),
                        Map.Entry::getValue,
                        (value1, value2) -> value1,
                        HashMap::new));
    }

    private static String convertHyphenToCamelCase(String hyphenatedString) {
        StringBuilder camelCaseBuilder = new StringBuilder();
        boolean capitalizeNext = false;

        for (char c : hyphenatedString.toCharArray()) {
            if (c == '-') {
                capitalizeNext = true;
            } else {
                if (capitalizeNext) {
                    camelCaseBuilder.append(Character.toUpperCase(c));
                    capitalizeNext = false;
                } else {
                    camelCaseBuilder.append(c);
                }
            }
        }

        return camelCaseBuilder.toString();
    }

}
